package cn.nexttec.noteplayer.injection

import android.annotation.SuppressLint
import android.content.Context
import android.content.SharedPreferences
import android.os.Build
import android.os.Environment
import android.os.Handler
import android.os.Looper
import cn.nexttec.noteplayer.BuildConfig
import cn.nexttec.noteplayer.common.GsonProvider
import cn.nexttec.noteplayer.common.Preference
import com.google.gson.Gson
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import java.io.File
import java.text.SimpleDateFormat
import java.time.format.DateTimeFormatter
import javax.inject.Named
import javax.inject.Singleton

@Module
@InstallIn(SingletonComponent::class)
class AppModule {

    @Singleton
    @Provides
    fun providePreference(@ApplicationContext context: Context):Preference{
        Preference.init(context)
        return Preference.getInstance()
    }

    @Singleton
    @Provides
    fun provideGson(): Gson {
        return GsonProvider.gson
    }

    @SuppressLint("SimpleDateFormat")
    @Singleton
    @Provides
    fun provideDateFormatter(): DateTimeFormatter {
        return DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
    }

    @Singleton
    @Provides
    fun provideHandler(): Handler {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            Handler.createAsync(Looper.getMainLooper())
        } else {
            Handler(Looper.getMainLooper())
        }
    }

    @IoDispatcher
    @Provides
    @Singleton
    fun provideIoDispatcher(): CoroutineDispatcher = Dispatchers.IO

    @DefaultDispatcher
    @Provides
    @Singleton
    fun provideDefaultDispatcher(): CoroutineDispatcher = Dispatchers.Default

    @MainDispatcher
    @Provides
    @Singleton
    fun provideMainDispatcher(): CoroutineDispatcher = Dispatchers.Main


    @Provides
    @Singleton
    @Named("BaseDir")
    fun provideNoteDir(@ApplicationContext context: Context): File {
//        if (BuildConfig.BUILD_TYPE == "debug"){
//            val result =  File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS),"Notes")
//            if (result.exists().not()){
//                result.mkdirs()
//            }
//            return result
//        } else {
            return context.filesDir
//        }
    }

    @Provides
    @Singleton
    @Named("TempDir")
    fun provideTempDir(@Named("BaseDir") baseDir:File): File {
        val dir =  File(baseDir, "Temp")
        if (dir.exists().not()){
            dir.mkdirs()
        }
        return dir
    }



}